package com.molichuxing.services.infrastructure.service.impl;

import com.molichuxing.services.business.dto.response.ThirdMotDto;
import com.molichuxing.services.infrastructure.bean.MotLogBean;
import com.molichuxing.services.infrastructure.convertor.Convert;
import com.molichuxing.services.infrastructure.dao.MotLogMapper;
import com.molichuxing.services.infrastructure.dto.request.create.ThirdMotCreateDto;
import com.molichuxing.services.infrastructure.service.MotLogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("motLogService")
public class MotLogServiceImpl implements MotLogService {

    private static final Logger logger = LoggerFactory.getLogger(MotLogServiceImpl.class);

    @Resource
    MotLogMapper motLogMapper;

    @Override
    public Integer createMot(ThirdMotCreateDto createDto) {
        logger.info("第三方年检 - 新增入库 - {}",createDto);
        MotLogBean log = new MotLogBean();
        log = Convert.toMotLogBean(createDto);
        return motLogMapper.create(log);
    }

    @Override
    public List<ThirdMotDto> getListByCarIds(List<Integer> carIds){
        logger.info("第三方年检 - 通过车辆id集合查询 - {}",carIds);
        List<MotLogBean> list = motLogMapper.getList(carIds);
        if(list!=null && list.size()>0){

            Map<Integer,ThirdMotDto> motMap = new HashMap<>();

            List<ThirdMotDto> reslist = new ArrayList<>();
            for (MotLogBean motLogBean : list) {
                if(motLogBean!=null && motLogBean.getCarId()!=null){
                    Integer carId = motLogBean.getCarId();

                    ThirdMotDto dto = motMap.get(carId);
                    if(dto==null){
                        dto = new ThirdMotDto();
                        BeanUtils.copyProperties(motLogBean,dto);
                        motMap.put(carId,dto);
                    }else{
                        if(dto.getGmtCreate()!=null
                                && motLogBean.getGmtCreate()!=null
                                && dto.getGmtCreate().isBefore(motLogBean.getGmtCreate())){
                            ThirdMotDto tmp  = new ThirdMotDto();
                            BeanUtils.copyProperties(motLogBean,tmp);
                            motMap.put(carId,tmp);
                        }
                    }
                }
            }
            if(motMap.size()>0){
                reslist.addAll(motMap.values());
            }
            return reslist;
        }
        return null;
    }
}
